package com.poc.database;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.poc.log.Log;

public class DatabaseManager {

	static {
		try {
			Class.forName("org.postgresql.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			System.exit(0);
		}
	}
	
	private String url;
	private String user;
	private String password;
	
	private Connection connection;
	
	private Log log;
	
	public DatabaseManager(String url, String user, String password) throws SQLException {
		this.url = url;
		this.user = user;
		this.password = password;
		
		this.connection = DriverManager.getConnection(this.url, this.user,this.password); 
		this.connection.setAutoCommit(false);

		 try {
			this.log = new Log("execucao");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public ResultSet execute(String query) throws SQLException {
		try {
			this.log.append(query + "\n");
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return this.connection.createStatement().executeQuery(query);
	}
	
	public void executeUpdate(String query) throws SQLException {
		this.connection.createStatement().executeUpdate(query);
	}
	
	public void commit() throws SQLException{
		this.connection.commit();
	}
	
	public void finalize() throws SQLException {
//		try {
//			//this.log.close();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		//this.connection.close();
		
	}
	
	public void reset() {
		try {
			this.connection.rollback();
			this.connection = DriverManager.getConnection(this.url, this.user,this.password); 
			this.connection.setAutoCommit(false);
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
